package com.easemob.helpdesk.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.easemob.helpdesk.bean.BaseWebResV2;
import com.easemob.helpdesk.bean.BaseWebResult;
import com.easemob.helpdesk.bean.DispatchResult;
import com.easemob.helpdesk.bean.HouseKeeper;
import com.easemob.helpdesk.bean.PageWithRes;
import com.easemob.helpdesk.bean.User;
import com.easemob.helpdesk.fragment.OwnerFragment;
import com.easemob.helpdesk.listener.OnItemClickListener;
import com.easemob.helpdesk.utils.CommonUtils;
import com.easemob.helpdesk.utils.DialogUtils;
import com.easemob.helpdesk.utils.DisplayUtil;
import com.easemob.helpdesk.widget.AddrSearchView;
import com.easemob.helpdesk.widget.SwipeRefreshView;
import com.google.gson.JsonObject;
import com.housekeeperapp.BuildConfig;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.net.ApiService;
import com.net.BaseResponse;
import com.net.HKHttpUtils;
import com.net.HKResponseResultCallBack;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by wsj on 2018/4/10.
 */

public class DispachList extends BaseActivityV2 implements AddrSearchView.searchListener{

    @Override
    protected void initFindView() {
        btn_back=findViewById(R.id.rl_back);

        mListView=findViewById(R.id.owner_list);
        mSwipeRefreshView=findViewById(R.id.swipe_owner_layout);
        emptyView=findViewById(R.id.emptyView);
        errorItem=findViewById(R.id.rl_owner_error_item);
        query=findViewById(R.id.query);

        clearSearch=findViewById(R.id.search_clear);
        ll_right=findViewById(R.id.ll_right);
        filterText=findViewById(R.id.ib_add_task);
        searchIcon=findViewById(R.id.ib_menu_more);
        owner_view_name=findViewById(R.id.owner_view_name);
    }
    public RelativeLayout btn_back;
    private InputMethodManager inputMethodManager;
    public ListView mListView;
    public SwipeRefreshView mSwipeRefreshView;
    public View emptyView;
    public RelativeLayout errorItem;
    public EditText query;
    public ImageButton clearSearch;
    public LinearLayout ll_right;
    public TextView filterText;
    public ImageView searchIcon;
    public TextView owner_view_name;
    private List<HouseKeeper> mList;
    private StringAdapter mAdapter;

    private AddrSearchView addrSearchView;

    public static final int REQUEST_CODE_ALERT_DIALOG_ACCESS = 0x18;

    /**
     * 加载提示Dialog
     */
    public Dialog pd = null;

    private static int curPage = 1;
    private static int totalPage = 0;
    //搜索字符串
    private String search_str = "";

    private String village_str = "";
    private String unit_str = "";
    private String homeBuilding_str = "";
    private String status_str = "";


    private int isdispatch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispach_list);
        initFindView();

        mList = new ArrayList<>();

        isdispatch = getIntent().getIntExtra("isdispatch", -1);
        if(isdispatch == 0){//转单
            owner_view_name.setText("转单");
        }

        mAdapter = new StringAdapter();
        inputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

        mListView.setAdapter(mAdapter);

        // 设置颜色属性的时候一定要注意是引用了资源文件还是直接设置16进制的颜色，因为都是int值容易搞混
        // 设置下拉进度的背景颜色，默认就是白色的
        mSwipeRefreshView.setProgressBackgroundColorSchemeResource(android.R.color.white);
        // 设置下拉进度的主题颜色
        mSwipeRefreshView.setColorSchemeResources(R.color.colorAccent,
                android.R.color.holo_blue_bright, R.color.colorPrimaryDark,
                android.R.color.holo_orange_dark, android.R.color.holo_red_dark, android.R.color.holo_purple);

        mSwipeRefreshView.setItemCount(20);

        // 手动调用,通知系统去测量
        mSwipeRefreshView.measure(0, 0);
        mSwipeRefreshView.setRefreshing(true);

        initEvent();
        initData();

    }


    private void initEvent() {

        String strSearch ="请输入姓名";
        query.setHint(strSearch);
        query.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                if(arg1 == EditorInfo.IME_ACTION_SEARCH)
                {
                    search_str = arg0.getText().toString();
                    if(addrSearchView != null){
                        addrSearchView.clearViewData();
                    }

                    village_str = "";
                    unit_str = "";
                    homeBuilding_str = "";
                    status_str = "";
                    filterText.setTextColor(Color.parseColor("#ffffff"));
                    searchIcon.setImageResource(R.drawable.hk_select_icon);

                    initData();
                }
                return false;
            }

        });

        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {

                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();

                search_str = "";
                initData();
            }

        });

        if (getResources().getString(R.string.LI_XIAO_SHUANG).equals(MainActivity.productKey)){
            ll_right.setVisibility(View.GONE);
        }else {
            ll_right.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (addrSearchView == null) {
                        addrSearchView = new AddrSearchView(DispachList.this, DispachList.this, true);
                        addrSearchView.showSearchView();
                        hideSoftKeyboard();
                    } else {
                        if (addrSearchView.isShowing()) {
                            addrSearchView.hideSearchView();
                        } else {
                            addrSearchView.showView();
                            hideSoftKeyboard();
                        }
                    }
                }

            });
        }

        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }

        });

        // 下拉时触发SwipeRefreshLayout的下拉动画，动画完毕之后就会回调这个方法
        mSwipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData();
            }
        });

        // 设置下拉加载更多
        mSwipeRefreshView.setOnLoadMoreListener(new SwipeRefreshView.OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                loadMoreData();
            }
        });
    }

    private void loadMoreData() {

        if(totalPage < curPage){//如果超过页数后
            return;
        }

        curPage = curPage + 1;

        mSwipeRefreshView.setLoading(true);


        ApiService apiService = HKHttpUtils.getApiService();
        retrofit2.Call<BaseResponse<DispatchResult.PageWithResBean>> call = apiService.getHousekeeperList(MainActivity.ticket, String.valueOf(curPage), "20", search_str, village_str, homeBuilding_str, unit_str, status_str);
        call.enqueue(new HKResponseResultCallBack<DispatchResult.PageWithResBean>() {
            @Override
            public void onSuccess(DispatchResult.PageWithResBean pageWithResBean) {
                List<HouseKeeper> users = pageWithResBean.getRes();
                if(users.size() != 0){
                    mList.addAll(users);
                }else{
                    Toast.makeText(DispachList.this, "没有更多的数据", Toast.LENGTH_SHORT).show();
                }

//						Toast.makeText(getActivity(), "加载了" + 20 + "条数据", Toast.LENGTH_SHORT).show();
                // 加载完数据设置为不加载状态，将加载进度收起来
                mSwipeRefreshView.setLoading(false);
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                mSwipeRefreshView.setLoading(false);
                Toast.makeText(DispachList.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                mSwipeRefreshView.setLoading(false);
                Toast.makeText(DispachList.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });
//        OkHttpClient okHttpClient = new OkHttpClient();
//        RequestBody body = new FormBody.Builder()
//                .add("page", String.valueOf(curPage))
//                .add("pageSize", String.valueOf(20))
//                .add("search", search_str)
//                .add("village", village_str)
//                .add("homeBuilding", homeBuilding_str)
//                .add("unit", unit_str)
//                .add("status", status_str)
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "housekeeper/list")
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(DispachList.this, "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                final DispatchResult result = CommonUtils.parseJsonWithGson(response.body().string(), DispatchResult.class);
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        List<HouseKeeper> users = result.getData().getRes();
//                        if(users.size() != 0){
//                            mList.addAll(users);
//                        }else{
//                            Toast.makeText(DispachList.this, "没有更多的数据", Toast.LENGTH_SHORT).show();
//                        }
//
////						Toast.makeText(getActivity(), "加载了" + 20 + "条数据", Toast.LENGTH_SHORT).show();
//                        // 加载完数据设置为不加载状态，将加载进度收起来
//                        mSwipeRefreshView.setLoading(false);
//                    }
//                });
//
//            }
//        });

    }


    private void initData() {
//        OkHttpClient okHttpClient = new OkHttpClient();

        curPage = 1;



        showLoading("加载中...");

        ApiService apiService = HKHttpUtils.getApiService();
        retrofit2.Call<BaseResponse<DispatchResult.PageWithResBean>> call = apiService.getHousekeeperList(MainActivity.ticket, String.valueOf(curPage), "20", search_str, village_str, homeBuilding_str, unit_str, status_str);
        call.enqueue(new HKResponseResultCallBack<DispatchResult.PageWithResBean>() {
            @Override
            public void onSuccess(DispatchResult.PageWithResBean pageWithResBean) {
                hideLoading();

                mList.clear();
                mList.addAll(pageWithResBean.getRes());
                totalPage = pageWithResBean.getTotal_page();

                if(mList.size() == 0){
                    mListView.setVisibility(View.GONE);
                    emptyView.setVisibility(View.VISIBLE);
                }else{
                    mListView.setVisibility(View.VISIBLE);
                    emptyView.setVisibility(View.GONE);
                    mAdapter.notifyDataSetChanged();
                }

                // 加载完数据设置为不刷新状态，将下拉进度收起来
                if (mSwipeRefreshView.isRefreshing()) {
                    mSwipeRefreshView.setRefreshing(false);
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                hideLoading();
                Toast.makeText(DispachList.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                hideLoading();
                Toast.makeText(DispachList.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });


//        RequestBody body = new FormBody.Builder()
//                .add("page", String.valueOf(curPage))
//                .add("pageSize", String.valueOf(20))
//                .add("search", search_str)
//                .add("village", village_str)
//                .add("homeBuilding", homeBuilding_str)
//                .add("unit", unit_str)
//                .add("status", status_str)
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "housekeeper/list")
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
////				hideLoading();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        hideLoading();
//                        Toast.makeText(DispachList.this, "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//
//                final DispatchResult result = CommonUtils.parseJsonWithGson(response.body().string(), DispatchResult.class);
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//						hideLoading();
//
//                        mList.clear();
//                        mList.addAll(result.getData().getRes());
//                        totalPage = result.getData().getTotal_page();
//
//                        if(mList.size() == 0){
//                            mListView.setVisibility(View.GONE);
//                            emptyView.setVisibility(View.VISIBLE);
//                        }else{
//                            mListView.setVisibility(View.VISIBLE);
//                            emptyView.setVisibility(View.GONE);
//                            mAdapter.notifyDataSetChanged();
//                        }
//
//                        // 加载完数据设置为不刷新状态，将下拉进度收起来
//                        if (mSwipeRefreshView.isRefreshing()) {
//                            mSwipeRefreshView.setRefreshing(false);
//                        }
//                    }
//                });
//
//            }
//        });

    }

    public void showLoading(String text) {
        //显示登录提示对话框
        pd = DialogUtils.getLoadingDialog(this, text);
        pd.show();
    }

    public void hideLoading() {
        if(pd != null && pd.isShowing()){
            pd.dismiss();
        }
    }


    private void dispatchOrder(long id){
//        OkHttpClient okHttpClient = new OkHttpClient();

        showLoading("处理中...");
        int orderId = getIntent().getIntExtra("order_id", 0);

        ApiService apiService = HKHttpUtils.getApiService();
        retrofit2.Call<BaseResponse<Boolean>> call = apiService.dispatchOrder(MainActivity.ticket,String.valueOf(orderId),String.valueOf(id),String.valueOf(isdispatch));
        call.enqueue(new HKResponseResultCallBack<Boolean>() {
            @Override
            public void onSuccess(Boolean iboolean) {
                hideLoading();

                if(iboolean){
                    Toast.makeText(DispachList.this, isdispatch==0?"转单成功":"派单成功", Toast.LENGTH_SHORT).show();
                    MainApplication.getInstance().getEventEmitter().sendEvent("order.onload");
                    finish();
                }else{
                    Toast.makeText(DispachList.this, isdispatch==0?"转单失败":"订单已有管家接单，派单失败，正在为您刷新页面", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onGetDataFailed(int cd, String msg) {
                hideLoading();
                Toast.makeText(DispachList.this, "请求失败:"+msg, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailed(retrofit2.Call call, Throwable t) {
                hideLoading();
                Toast.makeText(DispachList.this, "请求失败", Toast.LENGTH_SHORT).show();
            }
        });


//        RequestBody body = new FormBody.Builder()
//                .add("id", String.valueOf(orderId))
//                .add("keeperId", String.valueOf(id))
//                .add("isDispatch", String.valueOf(isdispatch))
//                .build();
//
//        Request request = new Request.Builder()
//                .url(BuildConfig.API_URL + "order/dispatch")
//                .post(body)
//                .build();
//
//        Call call = okHttpClient.newCall(request);
//
//        call.enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                e.printStackTrace();
//				hideLoading();
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        Toast.makeText(DispachList.this, "请求失败", Toast.LENGTH_SHORT).show();
//                    }
//                });
//
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                hideLoading();
//
////                final BaseWebResV2 result = CommonUtils.parseJsonWithGson(response.body().string(), BaseWebResV2.class);
//                final JsonObject result = CommonUtils.parseJson(response.body().string());
//
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        int cd = result.getCd();
//                        if(result.get("data").getAsBoolean()){
//                            Toast.makeText(DispachList.this, isdispatch==0?"转单成功":"派单成功", Toast.LENGTH_SHORT).show();
//                            MainApplication.getInstance().getEventEmitter().sendEvent("order.onload");
//                            finish();
//                        }else{
//                            Toast.makeText(DispachList.this, isdispatch==0?"转单失败":"派单失败", Toast.LENGTH_SHORT).show();
//                        }
//
//                    }
//                });
//
//            }
//        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    void hideSoftKeyboard() {
        if (this.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (this.getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == Activity.RESULT_OK){
            if(requestCode == REQUEST_CODE_ALERT_DIALOG_ACCESS){
                long id = data.getLongExtra("order_id", 0);
                dispatchOrder(id);
            }
        }

    }

    @Override
    public void addrSearchRes(String search, String city, String curCityPinyin, String village, String building, String unit, String edit_str) {

        search_str = "";

        query.getText().clear();

        if(!curCityPinyin.equals("") && !village.equals("")){
            village_str = curCityPinyin + "_" + village;
        }else{
            village_str = "";
        }

        if(!building.equals("")){
            homeBuilding_str = building;
        }else{
            homeBuilding_str = "";
        }

        if(!building.equals("") && !unit.equals("")){
            unit_str = building + "-" + unit;
        }else{
            unit_str = "";
        }

        if(!edit_str.equals("")){
            status_str = edit_str;
        }else{
            status_str = "";
        }

        // 如果是清空的话
        if(search.equals("")){
            filterText.setTextColor(Color.parseColor("#ffffff"));
            searchIcon.setImageResource(R.drawable.hk_select_icon);
        }else{
            filterText.setTextColor(Color.parseColor("#FFF16D"));
            searchIcon.setImageResource(R.drawable.hk_select_icon_data);
        }

        initData();
    }

    /**
     * 初始化View
     */
    private static class ViewHolder
    {
        private ImageView icon;
        private TextView name;
        private TextView addr;
        private TextView servicing;
        private TextView sevicecount;
        private TextView notserviced;
    }

    /**
     * 适配器
     */
    private class StringAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mList.size();
        }

        @Override
        public HouseKeeper getItem(int position) {
            return mList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                convertView = View.inflate(DispachList.this, R.layout.item_dispach_list, null);
                viewHolder = new ViewHolder();
                viewHolder.icon = (ImageView) convertView.findViewById(R.id.avatar);
                viewHolder.addr = (TextView) convertView.findViewById(R.id.tv_agent);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                viewHolder.servicing = (TextView) convertView.findViewById(R.id.servicing);
                viewHolder.sevicecount = (TextView) convertView.findViewById(R.id.sevicecount);
                viewHolder.notserviced = (TextView) convertView.findViewById(R.id.notserviced);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }

            String keeper_name = mList.get(position).getKeeper_name();
            if(CommonUtils.isBlank(keeper_name)){
                keeper_name = "管家";
            }else{
                if(keeper_name.length() > 9){
                    keeper_name = keeper_name.substring(0, 9) + "...";
                }
            }

//            String true_name = mList.get(position).getTruename();
//            if(!CommonUtils.isBlank(true_name)){
//                viewHolder.name.setText(keeper_name + "("+ true_name + ")");
//            }else{
                viewHolder.name.setText(keeper_name);
//            }

            int isRest = mList.get(position).getIsRest();
            Integer serviceCount = mList.get(position).getServicingCount();

            if (isRest == 1){//休息中
                viewHolder.servicing.setVisibility(View.GONE);
                viewHolder.sevicecount.setVisibility(View.GONE);
                viewHolder.notserviced.setVisibility(View.VISIBLE);
            }else {
                if (serviceCount > 0){
                    viewHolder.sevicecount.setVisibility(View.VISIBLE);
                    viewHolder.sevicecount.setText(serviceCount+"单");
                }else {
                    viewHolder.sevicecount.setVisibility(View.GONE);
                }
                viewHolder.servicing.setVisibility(View.VISIBLE);
                viewHolder.notserviced.setVisibility(View.GONE);
            }

//            if(serviceCount > 0){
//                viewHolder.servicing.setVisibility(View.VISIBLE);
//                viewHolder.sevicecount.setVisibility(View.VISIBLE);
//                viewHolder.sevicecount.setText(serviceCount + "单");
//                viewHolder.notserviced.setVisibility(View.GONE);
//            }else{
//                if(isRest == 1){
//                    viewHolder.servicing.setVisibility(View.GONE);
//                    viewHolder.sevicecount.setVisibility(View.GONE);
//                    viewHolder.notserviced.setVisibility(View.VISIBLE);
//                }else{
//                    viewHolder.servicing.setVisibility(View.GONE);
//                    viewHolder.sevicecount.setVisibility(View.GONE);
//                    viewHolder.notserviced.setVisibility(View.GONE);
//                }
//            }

            String keeper_head = mList.get(position).getKeeper_head();
            if(!CommonUtils.isBlank(keeper_head)){
                keeper_head = keeper_head.substring(keeper_head.indexOf(",") + 1);
                byte[] bytes = Base64.decode(keeper_head, Base64.DEFAULT);

                Glide.with(DispachList.this).load(bytes)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE).placeholder(R.drawable.default_agent_avatar).error(R.drawable.default_agent_avatar)
                        .into(viewHolder.icon);

            }else{
                viewHolder.icon.setImageResource(R.drawable.default_agent_avatar);
            }

            String city = mList.get(position).getAdminCity();
            String village = mList.get(position).getAdminVillage();
            String unit = mList.get(position).getHomeUnit();
            String add = "";
            if (!TextUtils.isEmpty(city)){
                add += city;
            }

            if (!TextUtils.isEmpty(village)){
                add += village;
            }

            if (!TextUtils.isEmpty(unit)){
                add += unit;
            }
            viewHolder.addr.setText(add);

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 管家休息中
                    if(mList.get(position).getIsRest() == 1){
                        return;
                    }

                    Intent intent = new Intent(DispachList.this, AlertDialog.class);
                    intent.putExtra("order_id", mList.get(position).getId());
                    intent.putExtra("msg", "确定将订单派给 <font color=\"#ED5600\">"+mList.get(position).getKeeper_name()+"</font> 吗？");
                    intent.putExtra("okString", "确定");
                    intent.putExtra("cancelString", "暂不");
                    startActivityForResult(intent, REQUEST_CODE_ALERT_DIALOG_ACCESS);

                }
            });

            return convertView;
        }
    }


}
